/*
 * WeatherPopup.cpp
 *
 *  Created on: Nov 18, 2010
 *      Author: quan
 */

#include "WeatherPopup.h"
//#include "Player.h"
#include <string.h>
#include <stdlib.h>
#include <FXml.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>

using namespace Osp::Base;
using namespace Osp::Ui::Controls;
using namespace Osp::Graphics;
using namespace Osp::Media;
using namespace Osp::Base::Utility;
using namespace Osp::Net::Http;
using namespace Osp::Xml;
using namespace Osp::Locations;


WeatherPopup::WeatherPopup()
:__popUp(null),popUpUtil(null),__button1(null),__button2(null),__label1(null),__label2(null),__label4(null),__label5(null),__label6(null),__label7(null),
 __pSession(null),__temp(null),__humid(null),__speed(null),__pressure(null), bitmap(null),__cond(null),__url(null),__pSession2(null)//quan add 11/11
{
	// TODO Auto-generated constructor stub

}
void WeatherPopup::Construct(){
	__temp=new String();
	*__temp = -100;
	__humid=new String();
	__speed=new String();
	__pressure=new String();;
	__cond = new String();
	__url = new String();
}
WeatherPopup::~WeatherPopup() {
	// TODO Auto-generated destructor stub
	if(__pSession){delete __pSession;
		__pSession=null;}
	if(__pSession2){delete __pSession2;
			__pSession2=null;}

	delete __temp;
	delete __humid;
	delete __speed;
	delete __pressure;
	delete __cond;
	delete __url;
}

void
WeatherPopup::ShowPopup(int mode,String address, String cond, String temp, String humi, String wind, String Pres, String url)
{

		__popUp=new Popup();
		__popUp->Construct(L"IDP_WEATHER");

		__button1=static_cast<Button*>(__popUp->GetControl(L"IDC_BUTTON1"));

		__button2=static_cast<Button*>(__popUp->GetControl(L"IDC_BUTTON2"));
		__button2->SetActionId(ID_POPUP_BYE);
		__button2->AddActionEventListener(*this);

		__label1=static_cast<Label*>(__popUp->GetControl(L"IDC_LABEL1"));
		__label1->SetText(address);

		__label2=static_cast<Label*>(__popUp->GetControl(L"IDC_LABEL2"));
		__label2->SetText(cond);

//		__label3=static_cast<Label*>(__popUp->GetControl(L"IDC_LABEL3"));
		__label4=static_cast<Label*>(__popUp->GetControl(L"IDC_LABEL4"));
		__label4->SetText(temp+L"*c");

		__label5=static_cast<Label*>(__popUp->GetControl(L"IDC_LABEL5"));
		__label5->SetText(L"Humidity:"+humi);

		__label6=static_cast<Label*>(__popUp->GetControl(L"IDC_LABEL6"));
		__label6->SetText(L"Wind Speed:"+wind);

		__label7=static_cast<Label*>(__popUp->GetControl(L"IDC_LABEL7"));
		__label7->SetText(L"Pressure:"+Pres);

		if (mode==0)
		{
			delete popUpUtil;
			__popUp->SetShowState(true);
			__popUp->Show();
		}
		else GetImage(url);

}

void
WeatherPopup::HidePopup()
{
	if(__popUp)
	{
		delete __popUp;
		__popUp = null;
	}
}

void
WeatherPopup:: OnActionPerformed(const Osp::Ui::Control& source, int actionId)
{
	if ( actionId == ID_POPUP_BYE)
	{
		HidePopup();
	}
}

result
WeatherPopup::GetImage(String url)
{
	AppLog("Get Image");
	srcImageUrl.SetUri(url);
    image1.Construct();
	result r = image1.DecodeUrl( srcImageUrl,BITMAP_PIXEL_FORMAT_RGB565,180, 180, reqId, *this,16000);
	AppLog("DecodeUrl status: %s", GetErrorMessage(r));
	return r;
}

void
WeatherPopup::OnImageDecodeUrlReceived(RequestId reqId, Osp::Graphics::Bitmap *pBitmap, result r,
		const Osp::Base::String errorCode, const Osp::Base::String errorMessage)
{
	AppLog("OnImageDecodeUrlReceived");
	if (errorCode!=null)
	{
		AppLog("Error Code: %S", errorCode.GetPointer());
	}
	if (r == E_SUCCESS)
	{
		bitmap = new Bitmap();
		bitmap->Construct(*pBitmap,Rectangle(0, 0, 180, 180));
	}
    __button1->SetNormalBackgroundBitmap(*bitmap);
    delete bitmap;
	delete popUpUtil;
	__popUp->SetShowState(true);
	__popUp->Show();
}

void WeatherPopup::getWeatherByLatLon(String yLat, String yLon){
	result r=E_SUCCESS;
	start = 0;
	String hostAddr="http://a5459128563.api.wxbug.net/getLiveWeatherRSS.aspx?ACode=A5459128563&lat=";
	hostAddr.Append(yLat);
	hostAddr.Append("&long=");
	hostAddr.Append(yLon);
	hostAddr.Append("&UnitType=1");
	AppLog("%S",hostAddr.GetPointer());
	HttpTransaction* pTransaction = null;
		HttpRequest* pRequest = null;
		if(__pSession == null)
			{
				__pSession = new HttpSession();
				r = __pSession->Construct(NET_HTTP_SESSION_MODE_NORMAL, null, hostAddr, null);
				if (IsFailed(r))
					goto CATCH;
			}

			pTransaction = __pSession->OpenTransactionN();
			if (null == pTransaction)
			{
				r = GetLastResult();
				goto CATCH;
			}

			r = pTransaction->AddHttpTransactionListener(*this);
			if (IsFailed(r))
				goto CATCH;

			pRequest = const_cast<HttpRequest*>(pTransaction->GetRequest());
			if(pRequest == null)
			{
				r = GetLastResult();
				goto CATCH;
			}

			r = pRequest->SetUri(hostAddr);
			if(IsFailed(r))
				goto CATCH;

			r = pRequest->SetMethod(NET_HTTP_METHOD_GET);
			if(IsFailed(r))
				goto CATCH;

			r = pTransaction->Submit();
			if(IsFailed(r))
				goto CATCH;
			popUpUtil=new PopupUtil;
			popUpUtil->Initialize();
			popUpUtil->ShowPopup();
			return ;

		CATCH:
			return ;

}
void WeatherPopup::OnTransactionReadyToRead(Osp::Net::Http::HttpSession& httpSession, Osp::Net::Http::HttpTransaction& httpTransaction, int availableBodyLen)
{
	HttpResponse* pHttpResponse = httpTransaction.GetResponse();



	if (pHttpResponse->GetStatusCode() == NET_HTTP_STATUS_OK)
	{AppLog("Thanh cong");

		HttpHeader* pHttpHeader = pHttpResponse->GetHeader();

		String* tempHeaderString = pHttpHeader->GetRawHeaderN();

		ByteBuffer* pBuffer = pHttpResponse->ReadBodyN();
		char data[pBuffer->GetLimit()+1];
		pBuffer->SetPosition(0);
		pBuffer->GetArray((byte*)data, 0,pBuffer->GetLimit());
		data[pBuffer->GetLimit()] ='\0';
		xmlDoc* doc = null;
		doc = xmlParseMemory(data,pBuffer->GetLimit() + 1);
		AppLog("Lenght=%d\n",pBuffer->GetLimit());

//		xmlXPathContextPtr xpathCtx;
//		xmlXPathObjectPtr xpathObj;
//		/* Create xpath evaluation context */
//		xpathCtx = xmlXPathNewContext(doc);
//		if(xpathCtx == NULL)
//			{
//			AppLog("Error: unable to create new XPath context");
//			xmlFreeDoc(doc);
//			}
		if (start==1)
		{
						String citycode;
						xmlNodePtr channel = xmlDocGetRootElement(doc);
						StringUtil::Utf8ToString((char*)channel->name,citycode);
						AppLog("Name: %S",citycode.GetPointer());
						channel = channel->children;
						while(channel != null)
						{
						if(!xmlStrcmp(channel->name,(const xmlChar*)"locations"))
						{
						channel = channel->children;
						AppLog("Here");
					    		char* attri_citycode =  (char*)xmlGetProp(channel,(xmlChar*)"citycode");
					    		StringUtil::Utf8ToString(attri_citycode,citycode);
					    		getWeathersByCityCode(citycode);
					    		free(attri_citycode);
					    		break;
						}
						channel = channel->next;
						}
					delete tempHeaderString;
					delete pBuffer;
		}
		else
		{
			xmlXPathContextPtr xpathCtx;
			xmlXPathObjectPtr xpathObj;
			/* Create xpath evaluation context */
			xpathCtx = xmlXPathNewContext(doc);
			if(xpathCtx == NULL)
				{
				AppLog("Error: unable to create new XPath context");
				xmlFreeDoc(doc);
				}
		/* Evaluate xpath expression */
		xpathObj = xmlXPathEvalExpression((xmlChar*)"//rss//channel", xpathCtx);
			if(xpathObj == NULL)
			{
			    AppLog("Error: unable to evaluate xpath expression");
			    xmlXPathFreeContext(xpathCtx);
			    xmlFreeDoc(doc);
			    return;
			}
			if(xmlXPathNodeSetIsEmpty(xpathObj->nodesetval))
			{
					xmlXPathFreeObject(xpathObj);
			        AppLog("No result\n");
			        return;
			}
			String tmp;
			xmlNodePtr channel = xpathObj->nodesetval->nodeTab[0];
			channel = channel->xmlChildrenNode;

			while(channel != null)
			{if(!xmlStrcmp(channel->name,(const xmlChar*)"item"))
				{
					xmlNodePtr item = channel->xmlChildrenNode;
					while(item != null)
					{
						//quan add 18/11
						if(!xmlStrcmp(item->name,(const xmlChar*)"title"))
						{
							StringUtil::Utf8ToString((char*)item->children->content,tmp);
							Address = tmp;
						}
						//end
						if(!xmlStrcmp(item->name,(const xmlChar*)"description"))
						{
						StringUtil::Utf8ToString((char*)item->children->content,tmp);
						int a=0;
						int b=0;

						String strtemp="<b>Temperature:</b> ";
						String strhumid="<b>Humidity:</b> ";
						String strspeed="<b>Wind Speed:</b> ";
						String strpressure="<b>Pressure:</b> ";

						//quan add 18/11
						result r=tmp.IndexOf("<b>",1,a);
						AppLog("++++++++++++++Get condition+++++++++++++");
						if(r==E_SUCCESS)
						{
						AppLog("chan lam");
						tmp.IndexOf("</b> <br />",a,b);
						tmp.SubString(a+3,b-a-3,*__cond);
						AppLog("%S____%d",__cond->GetPointer(),__cond->GetCapacity());
						//AppLog("Condition=%s",cond);
						//pXmlClass->ShowMessage(cond);
						}
						r=tmp.IndexOf("img src=",1,a);
						if(r==E_SUCCESS)
						{
							AppLog("++++++++++Get ImageUrl+++++++++");
							tmp.IndexOf("gif",a,b);
							tmp.SubString(a+9,b+3-a-9,*__url);
							AppLog("%S",__url->GetPointer());
						}
						//end
						a=0;b=0;
						r=tmp.IndexOf(strtemp,1,a);
						AppLog("chan lam %d",a);
						if(r==E_SUCCESS){AppLog("chan lam");
						tmp.IndexOf(" ",a+20,b);
					tmp.SubString(a+20,b-a-20,*__temp);AppLog("chan lam");
					AppLog("%S____%d",__temp->GetPointer(),__temp->GetCapacity());



						}
						a=0;b=0;
						r=tmp.IndexOf(strhumid,1,a);
						if(r==E_SUCCESS){AppLog("chan lam");
						tmp.IndexOf("%",a+17,b);
											tmp.SubString(a+17,b-a-17+1,*__humid);AppLog("chan lam");
											AppLog("%S____%d",__humid->GetPointer(),__humid->GetCapacity());



												}
						a=0;b=0;
						r=tmp.IndexOf(strspeed,1,a);
						if(r==E_SUCCESS){AppLog("chan lam");
						tmp.IndexOf("km/h",a+19,b);
											tmp.SubString(a+19,b-a-19+4,*__speed);AppLog("chan lam");
											AppLog("%S____%d",__speed->GetPointer(),__speed->GetCapacity());



												}
						a=0;b=0;
												r=tmp.IndexOf(strpressure,1,a);
												if(r==E_SUCCESS){AppLog("chan lam");
												tmp.IndexOf("mb",a+17,b);
																	tmp.SubString(a+17,b-a-17+2,*__pressure);AppLog("chan lam");
																	AppLog("%S____%d",__pressure->GetPointer(),__pressure->GetCapacity());



																		}
							}
						item = item->next;
					}
				}
			channel = channel->next;
			}
			float temp=0;
			result r = Float::Parse(*__temp,temp);
			if ( r != E_NUM_FORMAT)
				{
				ShowPopup(1,Address,*__cond,*__temp,*__humid,*__speed,*__pressure,*__url);
				}
			else ShowPopup(0,"Sorry, can't get weather information!","","unknown","unknown","unknown","unknown","unknown");

		delete tempHeaderString;
		delete pBuffer;
	}
	}else {
		AppLog("%S",pHttpResponse->GetStatusText().GetPointer());
		ShowPopup(0,"Sorry, can't get weather information!","","unknown","unknown","unknown","unknown","unknown");
	}
	return;


}

void WeatherPopup::OnTransactionAborted(HttpSession& httpSession, HttpTransaction& httpTransaction, result r)
{
	AppLog("####### OnTransactionAborted! (%s)#######", GetErrorMessage(r));
	ShowPopup(0,"Sorry, can't get weather information!","","unknown","unknown","unknown","unknown","unknown");
	delete &httpTransaction;
}
void WeatherPopup::OnTransactionReadyToWrite(HttpSession& httpSession, HttpTransaction& httpTransaction, int recommendedChunkSize)
{
	AppLog("####### OnTransactionReadyToWrite! #######");
}

void WeatherPopup::OnTransactionHeaderCompleted(HttpSession& httpSession, HttpTransaction& httpTransaction, int headerLen, bool rs)
{
	AppLog("####### OnTransactionHeaderCompleted! #######");
}



void WeatherPopup::OnTransactionCompleted(HttpSession& httpSession, HttpTransaction& httpTransaction)
{
	AppLog("####### OnTransactionCompleted! #######");

	delete &httpTransaction;
}

void WeatherPopup::OnTransactionCertVerificationRequiredN(HttpSession& httpSession, HttpTransaction& httpTransaction, Osp::Base::String* pCert)
{
	AppLog("####### OnTransactionCertVerificationRequiredN! #######");
}


void
WeatherPopup::getCityCode(String CityName)
{
	result r=E_SUCCESS;
		String hostAddr="http://api.wxbug.net/getLocationsXML.aspx?ACode=A4469340673&SearchString=";
		hostAddr.Append(CityName);
		AppLog("%S",hostAddr.GetPointer());
		HttpTransaction* pTransaction = null;
			HttpRequest* pRequest = null;
			if(__pSession2 == null)
				{
				__pSession2 = new HttpSession();
					r = __pSession2->Construct(NET_HTTP_SESSION_MODE_NORMAL, null, hostAddr, null);
					if (IsFailed(r))
						goto CATCH;

				}

				pTransaction = __pSession2->OpenTransactionN();
				start = 1;
				if (null == pTransaction)
				{
					r = GetLastResult();
					goto CATCH;
				}

				r = pTransaction->AddHttpTransactionListener(*this);
				if (IsFailed(r))
					goto CATCH;

				pRequest = const_cast<HttpRequest*>(pTransaction->GetRequest());
				if(pRequest == null)
				{
					r = GetLastResult();
					goto CATCH;
				}

				r = pRequest->SetUri(hostAddr);
				if(IsFailed(r))
					goto CATCH;

				r = pRequest->SetMethod(NET_HTTP_METHOD_GET);
				if(IsFailed(r))
					goto CATCH;

				r = pTransaction->Submit();
				if(IsFailed(r))
					goto CATCH;
				return ;

			CATCH:
				return ;
}

void
WeatherPopup::getWeathersByCityCode(String citycode)
{
	start = 0;
	result r=E_SUCCESS;
		String hostAddr="http://a5459128563.api.wxbug.net/getLiveWeatherRSS.aspx?ACode=A5459128563&citycode=";
//		hostAddr.Append(Double::ToString(yLat));
		hostAddr.Append(citycode);
//		hostAddr.Append(Double::ToString(yLon));
		hostAddr.Append("&UnitType=1");
		AppLog("%S",hostAddr.GetPointer());
		HttpTransaction* pTransaction = null;
			HttpRequest* pRequest = null;
			if(__pSession == null)
				{
					__pSession = new HttpSession();
					r = __pSession->Construct(NET_HTTP_SESSION_MODE_NORMAL, null, hostAddr, null);
					if (IsFailed(r))
						goto CATCH;
				}

				pTransaction = __pSession->OpenTransactionN();
				if (null == pTransaction)
				{
					r = GetLastResult();
					goto CATCH;
				}

				r = pTransaction->AddHttpTransactionListener(*this);
				if (IsFailed(r))
					goto CATCH;

				pRequest = const_cast<HttpRequest*>(pTransaction->GetRequest());
				if(pRequest == null)
				{
					r = GetLastResult();
					goto CATCH;
				}

				r = pRequest->SetUri(hostAddr);
				if(IsFailed(r))
					goto CATCH;

				r = pRequest->SetMethod(NET_HTTP_METHOD_GET);
				if(IsFailed(r))
					goto CATCH;

				r = pTransaction->Submit();
				if(IsFailed(r))
					goto CATCH;
				popUpUtil=new PopupUtil;
				popUpUtil->Initialize();
				popUpUtil->ShowPopup();
				return ;

			CATCH:
				return ;

}
